package com.googlecode.placesapiclient.client.parser.impl;

import com.googlecode.placesapiclient.client.entity.Place;
import com.googlecode.placesapiclient.client.exception.ErrorCode;
import com.googlecode.placesapiclient.client.exception.ErrorCodeException;
import com.googlecode.placesapiclient.client.parser.JSONParser;
import com.googlecode.placesapiclient.client.util.Converter;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 */
public class PlaceListParser implements JSONParser {

    private static final Logger logger = Logger.getLogger(PlaceListParser.class.getName());
    private static final String RESULTS = "results";

    @Override
    @SuppressWarnings("unchecked")
    public List<Place> parse(JSONObject jsonObject) throws ErrorCodeException {
        try {
            if (!jsonObject.has(RESULTS)) {
                throw new ErrorCodeException(ErrorCode.INVALID_JSON_OBJECT, "Invalid JSONObject element");
            }
            JSONArray array = jsonObject.getJSONArray(RESULTS);

            List<Place> arrayList = new ArrayList<Place>();
            for (int i = 0; i < array.length(); i++) {

                Place place = Converter.convertJsonToPlace((JSONObject) array.get(i));
                logger.info(place.toString());
                arrayList.add(place);

            }
            return arrayList;
        } catch (Exception th) {
            logger.error("Error during parsing JSONObject", th);
            throw new ErrorCodeException(ErrorCode.INVALID_JSON_OBJECT, "Invalid JSONObject element");
        }
    }
}
